package com.xiashitech.agent.instrumentation.struts2.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSStruts2PackageCallDepth;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import static net.bytebuddy.matcher.ElementMatchers.*;
import static net.bytebuddy.matcher.ElementMatchers.returns;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static com.xiashitech.agent.instrumentation.struts2.XSStruts2ActionSingletons.instrumenter;

/**
 * Deprecated
 * 在初始化解析 struts.xml 时的插桩，此时，拿不到 bean class
 * 插桩点也是一个 package 执行一次，也非一次性全量
 */
public class XSStruts2PackageInstrumnentation implements TypeInstrumentation  {
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("com.opensymphony.xwork2.config.providers.XmlConfigurationProvider");
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
              named("addPackage")
             .and(takesArgument(0, named("org.w3c.dom.Element")))
             .and(isProtected())
             .and(returns(named("com.opensymphony.xwork2.config.entities.PackageConfig"))),
        XSStruts2PackageInstrumnentation.class.getName() + "$XSPackageAdvice");
    }

    public static class XSPackageAdvice {
        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.This Object configurationProvider,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSStruts2PackageInstrumnentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            callDepth = CallDepth.forClass(XSStruts2PackageCallDepth.class);
            if (callDepth.getAndIncrement() > 0) {
                return;
            }
            Context parentContext = currentContext();
            if (!instrumenter().shouldStart(parentContext, configurationProvider)) {
                return;
            }
            parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
            context = instrumenter().start(parentContext, configurationProvider);
            context = BaggageUtil.syncBaggage().build().storeInContext(context);
            scope = context.makeCurrent();
            durationPrinter.printElapseDuration("XSPackageAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.This Object configurationProvider,
                @Advice.Return Object resultPackage,
                @Advice.Thrown Throwable throwable,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSStruts2PackageInstrumnentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            if (callDepth.decrementAndGet() > 0) {
                return;
            }
            if (scope != null) {
                scope.close();
                instrumenter().end(context, resultPackage , configurationProvider, throwable);
            }
            durationPrinter.printElapseDuration("XSPackageAdvice e");
        }
    }
}
